/////////////////////////////////////////////////////////////////////
//	$file: $
//	$revision: $
//	$author: $
//	$datetime: $
//	first author: buggy

#include	<QFileDialog>
#include	<QDir>
#include	<QProcess>
#include	<QDebug>

#include	"SourceNavigatorApp.h"
#include	"SourceNavigator.h"
#include	"SourceTree.h"

///////////////////////////////////////////////////////////
//	Source Navigator Application
SourceNavigatorApp::SourceNavigatorApp(int& argc, char** argv)
	:	QApplication(argc, argv)
{
	_srcnav		= NULL;
	_scriptPath	= QDir(QApplication::applicationDirPath() + "/../PlugIns").absolutePath();
}

SourceNavigatorApp::~SourceNavigatorApp()
{
	if (NULL != _srcnav)
		delete _srcnav; 
}

bool SourceNavigatorApp::Initialize(const char* path)
{
	QString		root;

	if (NULL == path)
	{
		QFileDialog		dialog(NULL, "Choose source root directory", QDir::homePath());
		
		//dialog.setFileMode(QFileDialog::Directory);
		dialog.setFileMode(QFileDialog::DirectoryOnly);
		if (!dialog.exec())
			return false;

		root	= dialog.selectedFiles().at(0);
	}
	else
	{
		root	= QDir(path).absolutePath();
	}

	_srcnav	= new SourceNavigator(root);

	if (false == _srcnav->IsValid())
		return false;

	_srcnav->setWindowTitle(_srcnav->RootName() + "://...");
	_srcnav->move(0, 0);
	_srcnav->show();
	return true;
}

#define	SrcNavApp()		(static_cast<SourceNavigatorApp*>(qApp))

const SourceNavigator* SourceNavigatorApp::MainWidget()
{
	return SrcNavApp()->_srcnav;
}

void SourceNavigatorApp::OpenTextEditor(const QString& id, const QString& path, int startPosition/*= 0*/)
{
	QString cmd = QString("%1/editor_vim.sh %2 open %3 %4")
					.arg(SrcNavApp()->_scriptPath)
					.arg(id)
					.arg(path)
					.arg(startPosition);

	QProcess::execute(cmd);
}

void SourceNavigatorApp::CloseTextEditor(const QString& id, const QString& /*path*/)
{
	QString cmd = QString("%1/editor_vim.sh %2 close")
					.arg(SrcNavApp()->_scriptPath)
					.arg(id);

	QProcess::execute(cmd);
}

void SourceNavigatorApp::SaveTextEditorFile(const QString& id, const QString& /*path*/)
{
	QString cmd = QString("%1/editor_vim.sh %2 save")
					.arg(SrcNavApp()->_scriptPath)
					.arg(id);

	QProcess::execute(cmd);
}

void SourceNavigatorApp::MoveTextEditorWindow(const QString& id, const QString& /*path*/, int positionIndex)
{
	QString cmd = QString("%1/editor_vim.sh %2 pos %3")
					.arg(SrcNavApp()->_scriptPath)
					.arg(id)
					.arg(positionIndex);

	QProcess::execute(cmd);
}

void SourceNavigatorApp::OpenShellWindow(const QString& shellCommand/* = ""*/)
{
	QString cmd = QString("%1/shell_terminal.sh %2 %3")
					.arg(SrcNavApp()->_scriptPath)
					.arg(SrcNavApp()->_srcnav->RootName() + "<SHELL>")
					.arg(SrcNavApp()->_srcnav->RootPath());

	if (shellCommand.length() > 0)
		cmd	+= " " + shellCommand;

	qDebug() << cmd;
	QProcess::execute(cmd);
}
